#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import re

def fix_import_in_file(file_path):
    """修复单个文件中的导入问题"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 修复 ugettext_lazy 导入
        content = re.sub(
            r'from django\.utils\.translation import ugettext_lazy as _',
            'from django.utils.translation import gettext_lazy as _',
            content
        )
        
        # 修复 django.core.urlresolvers 导入
        content = re.sub(
            r'from django\.core\.urlresolvers import',
            'from django.urls import',
            content
        )
        
        # 修复 django.contrib.contenttypes.generic 导入
        content = re.sub(
            r'from django\.contrib\.contenttypes\.generic import GenericRelation',
            'from django.contrib.contenttypes.fields import GenericRelation, GenericForeignKey',
            content
        )
        
        content = re.sub(
            r'from django\.contrib\.contenttypes import generic',
            'from django.contrib.contenttypes.fields import GenericForeignKey',
            content
        )
        
        # 修复 GenericForeignKey 使用
        content = re.sub(
            r'generic\.GenericForeignKey',
            'GenericForeignKey',
            content
        )
        
        # 写回文件
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        
        print(f"修复完成: {file_path}")
        return True
        
    except Exception as e:
        print(f"修复失败 {file_path}: {e}")
        return False

def fix_all_python_files(directory):
    """修复目录中所有的Python文件"""
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.py'):
                file_path = os.path.join(root, file)
                fix_import_in_file(file_path)

if __name__ == '__main__':
    # 修复所有应用模块
    apps_dir = 'apps'
    if os.path.exists(apps_dir):
        print(f"开始修复 {apps_dir} 目录...")
        fix_all_python_files(apps_dir)
    
    # 修复第三方模块
    thirdparty_dir = 'thirdparty'
    if os.path.exists(thirdparty_dir):
        print(f"开始修复 {thirdparty_dir} 目录...")
        fix_all_python_files(thirdparty_dir)
    
    print("所有修复完成！") 